#!/bin/sh

if [ $# -eq 0 ]; then
    echo "usage: $0 <c-source-file>" >&2
    exit -1
else
    source_file=$1
fi

input=$(cat <<EOF
William 35 25000
Kishore 41 35000
Wallace 37 30000
Bruce 39 29999
EOF
)

output=$(cat <<EOF
William 35 28000
Kishore 41 35000
Wallace 37 30000
Bruce 39 32999
EOF
)

clean() {
    rm -f main work.txt .{expect,actual}.{stdout,stderr,work}.txt
}

fail() {
    if [ ! -z "$1" ]; then
        echo "$1"
    fi
    echo FAIL
    clean
    exit -1
}

run() {
    local case=$1
    local expect_code=$2
    gcc "$source_file" -o main && ./main 1>.actual.stdout.txt 2>.actual.stderr.txt
    local actual_code=$?
    if [ $expect_code -eq $actual_code ]; then
        diff .{expect,actual}.stdout.txt || fail "case $case stdout"
        diff .{expect,actual}.stderr.txt || fail "case $case stderr"
        if [ -e work.txt ]; then
            if [ ! -r work.txt ]; then
                chmod +r work.txt
            fi
            diff {.expect.,}work.txt || fail "case $case work.txt"
        fi
    else
        fail "case $case return code expected $expect_code actual $actual_code"
    fi
    clean
}

clean

# 1. work.txt文件缺失

touch .expect.stdout.txt
echo "Cannot open work.txt with r mode." > .expect.stderr.txt
run 1 1

# 2. work.txt没有读权限

touch .expect.stdout.txt
echo "Cannot open work.txt with r mode." > .expect.stderr.txt
echo "$input" > work.txt
chmod 000 work.txt
echo "$input" > .expect.work.txt
run 2 1

# 3. work.txt没有写权限

echo "$input" > .expect.stdout.txt
echo "$output" >> .expect.stdout.txt
echo "Cannot open work.txt with w mode." > .expect.stderr.txt
echo "$input" > work.txt
chmod -w work.txt
echo "$input" > .expect.work.txt
run 3 1

# 4. 正常流程

echo "$input" > .expect.stdout.txt
echo "$output" >> .expect.stdout.txt
touch .expect.stderr.txt
echo "$input" > work.txt
echo "$output" > .expect.work.txt
run 4 0

echo PASS
